<?php
/**
 * app端，推荐商品管理
 * Author: lyun
 * Date: 2019/4/8
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\App;

use App\Http\Controllers\Service\Wechat\RecommendProductV3Service;
use App\Http\Requests\App\RecommendProductV2IndexRequest;
use App\Models\Customer\DeviceAccount;
use App\Models\Panx\SkinDetector;
use App\Models\Store\HmSkinRecord;
use App\Models\Store\WaxSkinRecord;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;
use App\Services\Utils\Guard;
use Illuminate\Database\Eloquent\Collection;
use App\Http\Controllers\Controller;

class RecommendProductV3Controller extends Controller
{
    use ApiResponser,
        ApiChecker;

    const ROUTES = [
        'index' => 'app.recommend.product.v3.index',
    ];

    /**
     * app端，v3版推荐商品
     * @test
     * @param RecommendProductV2IndexRequest $request
     * @param RecommendProductV3Service $recommend_product_service
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(RecommendProductV2IndexRequest $request, RecommendProductV3Service $recommend_product_service)
    {
        /** @var DeviceAccount $device_account */
        $device_account = Guard::deviceAccount();
        $customer_id = $device_account->customer_id;
        $store_id = $device_account->store_id;

        $skin_detector_id = (int)$request->skin_detector_id;
        $type_skin_record_id = (int)$request->type_skin_record_id;
        $sex = $request->sex;

        // 检测肤质检测数据
        $sub_skin_record = $this->getSubSkinRecord($skin_detector_id, $type_skin_record_id);
            $this->checkItemExist($sub_skin_record);

        // 获取wax/hm/cam检测项的阶段分数对应的商品信息。
        $recommend_products = $recommend_product_service->getRecommendProducts($sub_skin_record, $skin_detector_id, $customer_id, $sex, $store_id);

        // 根据category_id分组商品
        $group_recommend_products = $recommend_product_service->transformRecommendProducts($recommend_products);

        return $this->response(compact('group_recommend_products'));
    }

    /**
     * @param $skin_detector_id
     * @param $type_skin_record_id
     * @return HmSkinRecord|HmSkinRecord[]|WaxSkinRecord|WaxSkinRecord[]|Collection|\Illuminate\Database\Eloquent\Model|null
     */
    private function getSubSkinRecord($skin_detector_id, $type_skin_record_id)
    {
        if ($skin_detector_id === SkinDetector::ID_WAX) {
            $skin_record = (new WaxSkinRecord)->find($type_skin_record_id);
        } else if ($skin_detector_id === SkinDetector::ID_HM) {
            $skin_record = (new HmSkinRecord)->find($type_skin_record_id);
        } else {
            $skin_record = null;
        }

        return $skin_record;
    }
}
